package cn.codexin.wechatofficial.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author ly
 * @date 2020/8/13 0013 11:19
 */
@Configuration
@MapperScan(basePackages = {"cn.codexin.wechatofficial.mapper.HTDB.dbo"},sqlSessionTemplateRef = "HTDBSqlSessionTemplate")
public class HTDBConfig {
    @Bean(name = "HTDBDataSource")
    @ConfigurationProperties(prefix = "spring.htdb.datasource")
    @Primary
    public DataSource HTDBDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "HTDBSqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("HTDBDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/HTDB/dbo/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "HTDBTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("HTDBDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "HTDBSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("HTDBSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
